from flask import Blueprint, render_template, request

from applications.common import curd
from applications.common.curd import model_to_dicts
from applications.common.helper import ModelFilter
from applications.common.utils.http import table_api, fail_api, success_api
from applications.common.utils.rights import authorize
from applications.common.utils.validate import xss_escape
from applications.extensions import db
from applications.models import Role, Scene
from applications.schemas import SceneOutSchema

admin_scene = Blueprint('adminScene', __name__, url_prefix='/admin/scene')


# 情景管理
@admin_scene.get('/')
#@authorize("admin:scene:main", log=True)
def main():
    return render_template('admin/scene/main.html')

# 情景分页查询
@admin_scene.get('/data')
def data():
    # 获取请求参数
    id = request.args.get('id', type=int)
    content = xss_escape(request.args.get('content', type=str))
    version = xss_escape(request.args.get('version', type=str))
    Sceneadmin = xss_escape(request.args.get('Sceneadmin', type=str))
    enable = request.args.get('enable', type=int)

    # 查询参数构造
    mf = ModelFilter()
    if id:
        mf.exact(field_name="id", value=id)
    if enable:
        mf.exact(field_name="enable", value=enable)
    if content:
        mf.contains(field_name="content", value=content)
    if version:
        mf.contains(field_name="version", value=version)
    if Sceneadmin:
        mf.contains(field_name="Sceneadmin", value=Sceneadmin)
    # orm查询
    # 使用分页获取data需要.items
    scene = Scene.query.filter(mf.get_filter(model=Scene)).layui_paginate()
    count = scene.total
    # 返回api
    return table_api(data=model_to_dicts(schema=SceneOutSchema, data=scene.items), count=count)

# 情景增加
@admin_scene.get('/add')
#@authorize("admin:scene:add", log=True)
def add():
    roles = Role.query.all()
    return render_template('admin/scene/add.html', roles=roles)


@admin_scene.post('/save')
#@authorize("admin:scene:add", log=True)
def save():
    req_json = request.json
    a = req_json.get("roleIds")
    content = xss_escape(req_json.get('content'))
    version = xss_escape(req_json.get('version'))
    Sceneadmin = xss_escape(req_json.get('Sceneadmin'))
    role_ids = a.split(',')

    if not content or not version or not Sceneadmin:
        return fail_api(msg="情景名字、情景版本、情景管理员不得为空")

    if bool(Scene.query.filter_by(content=content).count()):
        return fail_api(msg="情景已经存在")
    scene = Scene(content=content, version=version, Sceneadmin=Sceneadmin)
    db.session.add(scene)
    roles = Role.query.filter(Role.id.in_(role_ids)).all()
    for r in roles:
        scene.role.append(r)
    db.session.commit()
    return success_api(msg="增加成功")


# 删除情景
@admin_scene.delete('/remove/<int:id>')
@authorize("admin:scene:remove", log=True)
def delete(id):
    user = Scene.query.filter_by(id=id).first()
    user.role = []

    res = Scene.query.filter_by(id=id).delete()
    db.session.commit()
    if not res:
        return fail_api(msg="删除失败")
    return success_api(msg="删除成功")

#  编辑情景
@admin_scene.get('/edit/<int:id>')
@authorize("admin:scene:edit", log=True)
def edit(id):
    scene = curd.get_one_by_id(Scene, id)
    roles = Role.query.all()
    checked_roles = []
    for r in roles:
        checked_roles.append(r.id)
    return render_template('admin/scene/edit.html', scene=scene, roles=roles, checked_roles=checked_roles)


#  编辑情景
@admin_scene.put('/update')
@authorize("admin:scene:edit", log=True)
def update():
    req_json = request.json
    a = req_json.get("roleIds")
    id = xss_escape(req_json.get("id"))
    content = xss_escape(req_json.get('content'))
    version = xss_escape(req_json.get('version'))
    Sceneadmin = xss_escape(req_json.get('Sceneadmin'))
    role_ids = a.split(',')
    Scene.query.filter_by(id=id).update({'content': content, 'version': version, 'Sceneadmin': Sceneadmin})
    u = Scene.query.filter_by(id=id).first()

    roles = Role.query.filter(Role.id.in_(role_ids)).all()
    u.role = roles

    db.session.commit()
    return success_api(msg="更新成功")


# 批量删除
@admin_scene.delete('/batchRemove')
@authorize("admin:scene:remove", log=True)
def batch_remove():
    ids = request.form.getlist('ids[]')
    for id in ids:
        user = Scene.query.filter_by(id=id).first()
        user.role = []

        res = Scene.query.filter_by(id=id).delete()
        db.session.commit()
    return success_api(msg="批量删除成功")